package com.ruicar.afs.cloud.gateway.handler;

import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.constant.SecurityConstants;
import com.ruicar.afs.cloud.common.core.util.Base64Util;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Fzero
 * @date 2019-01-24
 * 验证码生成逻辑处理类
 */
@Slf4j
@Component
@AllArgsConstructor
public class CaptchaCodeHandler implements HandlerFunction<ServerResponse> {
	private final RedisTemplate redisTemplate;
	private static final Integer DEFAULT_IMAGE_WIDTH = 100;
	private static final Integer DEFAULT_IMAGE_HEIGHT = 40;

	@Override
	public Mono<ServerResponse> handle(ServerRequest serverRequest) {
		//生成验证码
		ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);

		//保存验证码信息
		String udidKey = UUID.randomUUID().toString().replaceAll("-", "");
		redisTemplate.opsForValue().set(CommonConstants.DEFAULT_CODE_KEY + udidKey, captcha.text()
				, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);

		log.info("random=>{},val=>{},code=>{}", udidKey,captcha.getArithmeticString(), captcha.text());

		// 转换流信息写出
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		captcha.out(os);

		return ServerResponse
				.status(HttpStatus.OK)
				.contentType(MediaType.APPLICATION_JSON)
				.body(BodyInserters.fromValue(
						IResponse.success(
								CaptchaCode.builder().key(udidKey).data("data:image/jpeg;base64," + Base64Util.encode(os.toByteArray())).build()
						)));
	}

	@Data
	@Builder
	public static class CaptchaCode {
		String key;
		String data;
	}
}
